package 第五周;

/**
 * @author xhw
 */

public class 最长有效括号 {
    public static void main(String[] args) {
        String s = ")(";
        System.out.println(longestValidParentheses(s));
    }

    public static int longestValidParentheses(String s) {
        int left = 0, right = 0, maxLength = 0;

        // 正向遍历
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == '(') {
                left++;
            } else {
                right++;
            }

            if (left == right) {
                maxLength = Math.max(maxLength, 2 * right);
            } else if (right > left) {
                left = right = 0;
            }
        }

        // 在进行反向遍历之前重置计数器
        left = right = 0;
        // 反向遍历
        for (int i = s.length() - 1; i >= 0; i--) {
            if (s.charAt(i) == '(') {
                left++;
            } else {
                right++;
            }

            if (left == right) {
                maxLength = Math.max(maxLength, 2 * left);
            } else if (left > right) {
                left = right = 0;
            }
        }

        return maxLength;
    }
}
